package com.wk.springboot.filter;

import com.wk.springboot.util.HttpUtil;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

/**
 * @Classname DiskReturnFilter
 * @Description 本地磁盘返回报文过滤器
 * @Date 2019/11/27 11:11
 * @Author by weikai
 */

public class DiskReturnFilter extends FileAlterationListenerAdaptor {

  private Logger log = LoggerFactory.getLogger(DiskReturnFilter.class);

  @Value("target.toFile")
  String toFilePath;

  /**
   * 文件创建执行
   */
  @Override
  public void onFileCreate(File file) {
    log.info("++++++++新增文件，路径是:{}" + file.getAbsolutePath());
    log.info("要传输到:{}", toFilePath);
/*    File toFile = new File(toFilePath);
    try{
      FileUtils.copyFile(file,toFile);
      log.info("+++++++++++++移动文件成功了");
    }catch (Exception e){
      log.error("++++++++++create移动文件出错了",e);
    }*/
    String url = "http://172.16.192.184:8090/transfer/receive";

    try {
      HttpUtil.sendFileByMultipartEntityBuilder(url, file);
    } catch (IOException e) {
      System.out.println("出错了");
    }

  }

  /**
   * 文件删除
   */
  @Override
  public void onFileDelete(File file) {
    log.info("监听返回报文路径删除:{}" + file.getAbsolutePath());
  }

  @Override
  public void onFileChange(final File file) {
    log.info("++++++++修改文件:{}" + file.getAbsolutePath());
    log.info("要传输到:{}", toFilePath);
    File toFile = new File(toFilePath);
    try {
      FileUtils.copyFile(file, toFile);
      log.info("+++++++++++++移动文件成功了");
    } catch (Exception e) {
      log.error("+++++++++++update移动文件出错了", e);
    }
  }

}
